﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Input;

namespace JMT.Controls
{
    public class JMTextBox : TextBox
    {
        public JMTextBox()
        {
            GoToReadonly();
        }

        protected override void OnMouseDoubleClick(System.Windows.Input.MouseButtonEventArgs e)
        {
            if (IsReadOnly)
            {
                GoToEdit();
            }

            //base.OnMouseDoubleClick(e);
        }

        protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Escape)
            {
                GoToReadonly();
            }
            else if (e.Key == Key.Enter)
            {
                GoToReadonly();
            }

            base.OnKeyDown(e);
        }

        private void GoToReadonly()
        {
            this.Margin = new System.Windows.Thickness(2);
            this.BorderThickness = new System.Windows.Thickness(0);
            this.IsReadOnly = true;
            this.Cursor = Cursors.Arrow;
            this.IsTabStop = false;
            this.Focusable = false;
        }

        private void GoToEdit()
        {
            this.Margin = new System.Windows.Thickness(1);
            this.BorderThickness = new System.Windows.Thickness(1);
            this.IsReadOnly = false;
            this.Cursor = Cursors.IBeam;
            this.IsTabStop = true;
            this.Focusable = true;
            this.Focus();
            this.SelectAll();
        }

        protected override void OnMouseDown(MouseButtonEventArgs e)
        {
            if (IsReadOnly)
            {
                e.Handled = false;
            }
            else
            {
                base.OnMouseDown(e);
            }
        }
    }
}
